package com.http.method;

import android.os.Handler;

import com.alibaba.fastjson.JSONObject;
import com.http.callback.RequestCallBack;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.util.HashMap;

/**
 * Created by mac_wk on 14-12-9.
 */
public class JsonRequest<T> extends Request<T> {
    private String type = CommonRequestType.JSON;
    private Class clazz;

    public JsonRequest(String mUrl) {
        super(mUrl);
    }

    public JsonRequest(String mUrl, Class clazz, RequestCallBack requestCallBack) {
        super(mUrl, requestCallBack);
        this.clazz = clazz;
    }
    public JsonRequest(String mUrl,Class clazz,Handler handler1)
    {
        super(mUrl,null,handler1);
        this.clazz = clazz;

    }

    @Override
    public void setRequestType(String type) {
        this.type = type;
    }

    @Override
    public String getRequestType() {
        return type;
    }

    @Override
    public void executeRequest(HttpURLConnection httpURLConnection) throws IOException {
        RequestResult requestResult = new RequestResult();
            int code = httpURLConnection.getResponseCode();
            String message = parseHttpUrlConnection(httpURLConnection);
            switch (code) {
                case 200:
                    T t = null;
                    if (clazz != null)
                    {
                        t = (T) JSONObject.parseObject(message, clazz);
                    }
                    requestResult.requestCallBack = requestCallBack;
                    requestResult.obj = t;
                    handler.obtainMessage(SUCCESS,requestResult).sendToTarget();
                    break;
                default:
                    requestResult.requestCallBack = requestCallBack;
                    requestResult.status_code = httpURLConnection.getResponseCode();
                    requestResult.obj = message;
                    handler.obtainMessage(ERROR,requestResult);
                    break;
            }

    }


    @Override
    public int compareTo(Request<T> another) {
        return 0;
    }
}
